package com.example.asus.facerecognitiondemo;

import android.graphics.Bitmap;
import android.util.Log;

import com.megvii.cloud.http.CommonOperate;
import com.megvii.cloud.http.FaceSetOperate;
import com.megvii.cloud.http.Response;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

public class DetectDemo {
    public interface Callback{
        void success(JSONObject result);
        void error(Exception exception);
    }

    public static void detect(final Bitmap bitmap, final Callback callback){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //request
                    CommonOperate commonOperate = new CommonOperate(Constant.key,Constant.secret, false);
                    FaceSetOperate FaceSet = new FaceSetOperate(Constant.key,Constant.secret, false);
                    ArrayList<String> faces = new ArrayList<>();

                    Bitmap bmSmall = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight());
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();

                    bmSmall.compress(Bitmap.CompressFormat.JPEG,100,stream);

                    byte[] arrays = stream.toByteArray();
                    Response response1 = commonOperate.detectByte(arrays, 0, "age,gender");
                    String faceToken1 = new String(response1.getContent());
                    JSONObject jsonObject = new JSONObject(faceToken1);

                    Log.e("TAG",jsonObject.toString());
                    if (callback!=null){
                        callback.success(jsonObject);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (callback!=null){
                        callback.error(e);
                    }
                }
            }
        }).start();
    }
}
